from django.shortcuts import render
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from orders.models import OrderInfo
from rest_framework import status
from rest_framework.response import Response
from alipay import AliPay
from django.conf import settings
import os
from .models import Payment

# Create your views here.


class PaymentView(APIView):
    """发起支付"""
    permission_classes = [IsAuthenticated]

    def get(self, request, order_id):
        # 校验传来的订单号
        try:
            order = OrderInfo.objects.get(order_id=order_id,user=request.user,
                                     pay_method=OrderInfo.PAY_METHODS_ENUM['ALIPAY'],
                                     status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except OrderInfo.DoesNotExist:
            return Response({'message': '订单信息有误'}, status=status.HTTP_400_BAD_REQUEST)
        # 调用支付宝的链接， 客户端的调用 cliet, 是网站的
        alipay_client = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                              "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem"),  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.ALIPAY_DEBUG  # 默认False
        )

        # 网站的支付宝客户端的函数， 生成交易的流水号
        order_string = alipay_client.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject="美多商城%s" % order_id,
            return_url="http://www.meiduo.site:8080/pay_success.html",
        )
        # xxxxxxxxx, 拼接链接， 返回客户端的
        alipay_url = settings.ALIPAY_URL + "?" + order_string
        return Response({'alipay_url': alipay_url})


class PaymentStatus(APIView):
    """保存支付信息,支付状态"""

    def put(self, request):
        # 获取前端来的查询想字符串参数,转化为dict
        data = request.query_params.dict()
        sign = data.pop('sign')

        order_id = data.get('out_trade_no')
        trade_id = data.get('trade_no')
        print(trade_id)

        # 调用支付宝的链接， 客户端的调用 cliet, 是网站的
        alipay_client = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                              "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem"),  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.ALIPAY_DEBUG  # 默认False
        )
        # 调用校验的接口，校验订单信息以及交易流水是否正确
        success = alipay_client.verify(data, sign)
        if success:
            # 若正确， 修改支付的状态，从为支付转为待发货，
            OrderInfo.objects.filter(order_id=order_id, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']).update(status=OrderInfo.ORDER_STATUS_ENUM['UNSEND'])
            # 创建支付的数据
            Payment.objects.create(
                order_id=order_id,
                trade_id=trade_id
            )
        # 返回交易流水号给用户
            return Response({'trade_id': trade_id})

        else:
            # 若不正确， 抛出异常
            return Response({'message': '非法请求'}, status=status.HTTP_403_FORBIDDEN)
